import { useState, useCallback, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useParams,useNavigate } from "react-router-dom";
import { showNotification } from '../common/headerSlice'
import CompanyService from "../../app/services/companyService";
import CommonService from "../../app/services/commonService";
import TitleCard from "../../components/Cards/TitleCard";
import InputText from "../../components/Input/InputText";
import ToogleInput from "../../components/Input/ToogleInput";
import { NotificationManager} from 'react-notifications';
import _ from "lodash";

const DepartmentEdit = () => {
  const dispatch = useDispatch();
  const params = useParams();
  const navigate = useNavigate();

  const [company, setCompany] = useState({
    companyName: "",
    companyAddress: "",
    companyShortName: "",
    contactName: "",
    companyPhone: "",
    status: false
  });

  const [loading, setLoading] = useState(false)
  const [title,setTitle] = useState('编辑机构信息')
  const [updateButtonTitle,setUpdateButtonTitle] = useState('保存')
  const [successMessage,setSuccessMessage] = useState('保存机构成功')
  const [setErrorMessgae,setErrorMessage] = useState('保存机构失败')

  const fetchData = useCallback((item) => {
    
    CommonService.setLoading(true);
    CompanyService.byId(item.id).then((res) => {
      setCompany(prev => ({
        ...prev,
        companyName: res.companyName || '',
        companyAddress: res.companyAddress || '',
        companyShortName: res.companyShortName || '',
        contactName: res.contactName || '',
        contactPhone: res.contactPhone || '',
        status: res.status,
      }));
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }, [params.id]);

  useEffect(() => {
    if(!params) {
      return
    }
    if(params.id === '0' ) {
      setTitle("新建机构")
      setUpdateButtonTitle('创建新机构')
      setSuccessMessage('新建机构成功')
      setErrorMessage('新建机构失败')
      return
    } else {
      setTitle("编辑机构信息")
      setUpdateButtonTitle('保存')
      setSuccessMessage('保存机构成功')
      setErrorMessage('保存机构失败')
    }
    fetchData(params);
  }, [params.id]);

  const updateFormValue = ({ updateType, value }) => {
    setCompany(prevCompany => ({
      ...prevCompany,
      [updateType]: value,
    }));
  }

  const updateCompany = () => {
    CommonService.setLoading(true);
    var validateResult = ValidatorForm()
    console.log(validateResult)
    if (!validateResult) {
      CommonService.setLoading(false);
      return
    }
    var func = CompanyService.update
    if(params.id === '0') {
      func = CompanyService.create
    }
    func({...company,'id':params.id}).then((res) => {
      if (res) {
        NotificationManager.success(successMessage, '提示');
        navigate("/app/departments");
      } else {
        NotificationManager.error(setErrorMessgae, '提示');
      }
    }).catch(err=> {
      console.log(err)
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }

  const ValidatorForm = () => {
    var errorMessage = ''
    if (company.contactPhone === "") {
      errorMessage = "联系电话不能为空"
    }
    if(!CommonService.validatePhoneNumber(company.contactPhone)) {
      errorMessage = "联系电话格式不正确"
    }
    if (!CommonService.validateStringLength(company.contactName, 2, 5)) {
      errorMessage = "公司联系人姓名长度应该在2~5位之间"
    }
    if (!CommonService.validateStringLength(company.companyShortName, 2, 2)) {
      errorMessage = "公司简称长度应为2位"
    }
    if (!CommonService.validateStringLength(company.companyName, 5, 50)) {
      errorMessage = "公司名称应长度在5~50位之间"
    }
    
    if (errorMessage !== '') {
      NotificationManager.error(errorMessage, '提示');
      return false
    }

    return true
  }



  return (
    <>
      <div className="flex flex-col">
        {company && <TitleCard title={title} topMargin="mt-2">
          <div className="flex flex-col p-2">
            <InputText labelTitle="公司名称" updateType="companyName" defaultValue={company.companyName} updateFormValue={updateFormValue} />
            <InputText labelTitle="公司地址" updateType="companyAddress" defaultValue={company.companyAddress} updateFormValue={updateFormValue} />
            <InputText labelTitle="公司简写" updateType="companyShortName" defaultValue={company.companyShortName} updateFormValue={updateFormValue} />
            <InputText labelTitle="联系人" updateType="contactName" defaultValue={company.contactName} updateFormValue={updateFormValue} />
            <InputText labelTitle="联系电话" updateType="contactPhone" defaultValue={company.contactPhone} updateFormValue={updateFormValue} />
            <ToogleInput labelTitle="状态" updateType="status" defaultValue={company.status} updateFormValue={updateFormValue} />
          </div>
          <div className="mt-16"><button className={`btn btn-primary float-right   ${loading ? " loading" : ""}`} onClick={() => updateCompany()}>{updateButtonTitle}</button></div>
        </TitleCard>
        }
      </div>
    </>
  );
}

export default DepartmentEdit;
